from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from ad_manage.models import Advertisement
import logging
from django.forms.models import model_to_dict
from django.db.models import Q
import pickle

import numpy as np
import numpy as np

@csrf_exempt
def upload_image(request):
    if request.method == 'POST':
        file = request.FILES['file']

        print(type(file))

    return JsonResponse({'json_data': 'success'})


def upload_test(request):
    return render(request, 'html/main/upload_image.html', None)


def get_all_tag(request):
    advertisements = Advertisement.objects.exclude(local_img='暂无').exclude(local_img='')[0:100]
    for advertisement in advertisements:
        print('test')

    return JsonResponse({'json_data': 'success'})

import csv

def select_same_image_test(request):


    id = int(request.GET.get('id'))
    advertisement_feature = Advertisement.objects.filter(id=id).values_list('image_feature',flat=True)
    lo = pickle.loads(advertisement_feature[0])
    cur_feature_arr = np.array(lo)

    if (advertisement_feature[0]!=None):

        same_advertisement = Advertisement.objects.exclude(id=id).exclude(image_feature__isnull=True).values_list(
            'image_feature')[0:1000]

        sa_list = []
        for s in same_advertisement:
            s0 = pickle.loads(s[0])
            a = pickle.loads(s[0])
            sa_list.append(np.array(a))
        sa_arr = np.array(sa_list)
        print(sa_arr)
        print(sa_arr.shape)

        np.save('/repo/smspider/images/feature_arr.npy', sa_arr)
        data = np.load('/repo/smspider/images/feature_arr.npy')

        scores = np.dot(cur_feature_arr, data.T)
        rank_ID = np.argsort(scores)[::-1]
        print(rank_ID)
        # ad_list = np.array(advertisement_feature)
        #
        # same_advertisement = Advertisement.objects.exclude(id=id).exclude(image_feature__isnull=True).values_list('image_feature')
        # # count = same_advertisement.count()
        # count = 2500
        # page = count//1000
        # path = "F:/test/bb.csv"
        # for p in range(page):
        #     way = "a"
        #     if(page==0):
        #         way="w"
        #     for s in same_advertisement[1000*page:(page+1)*1000]:
        #         with open(path, way, newline='') as csvfile:
        #             writer = csv.writer(csvfile)
        #             data = (pickle.loads(s[0]))
        #             writer.writerow(data)
        # for s in same_advertisement[page*1000:count-1]:
        #     with open(path, "a", newline='') as csvfile:
        #         writer = csv.writer(csvfile)
        #         data = (pickle.loads(s[0]))
        #         writer.writerow(data)


        # same_ad_list = np.array(pickle.loads(same_advertisement))
        #
        # scores = np.dot(ad_list, same_ad_list)
        # rank_ID = np.argsort(scores)[::-1]
        return JsonResponse({'json_data': 'feature is null'})
    else:
        return JsonResponse({'json_data': 'feature is null'})


def select_same_image(request):
    page = int(request.GET.get('page'))
    pagesize = 10
    start = (page - 1) * 10
    end = page * 10
    ad_id = request.GET.get("id")
    id = int(request.GET.get('id'))
    advertisement = Advertisement.objects.filter(id=id)[0]
    Advertisement.objects.exclude(id=id).values('image_feature')
    if (advertisement.image_feature != None):
        result_list = []
        sa_dict = []
        for x in range(5):
            tag = '{}{}'.format('image_tag_', x+1)  # x值表示当前图片的十个标签的下标,image_tag_1,image_tag_2,image_tag_3...... #

            tag_value = getattr(advertisement,tag)
            # for y in range(10):
            #     sa_tag = '{}{}'.format('image_tag_', y)
            q = Q()
            q.add(Q(**{"image_tag_1": tag_value}), Q.OR)
            same_advertisement = Advertisement.objects.exclude(image_feature__isnull=True).exclude(id=ad_id).filter(q)[
                                 start:end]  # 实现动态字段的查询 #
            if same_advertisement.count()>0:
                m = [model_to_dict(item) for item in same_advertisement]
                sa_dict.extend(m)
                # 计算特征码的內积 #
                for sa in same_advertisement:
                    sa_feature = sa.image_feature
                    result = np.dot(pickle.loads(sa_feature),
                                    pickle.loads(advertisement.image_feature))
                    result_list.append(result)
                if len(sa_dict) < 10 :
                    start = 0
                    end = 10- len(sa_dict)
                    continue
                else:
                    break
        # 冒泡排序 越接近1的越相似
        lenth = len(result_list)
        for i in range(lenth):
            for j in range(lenth - i - 1):
                if result_list[j] < result_list[j + 1]:
                    temp = result_list[j]
                    result_list[j] = result_list[j + 1]
                    result_list[j + 1] = temp
                    sa_temp = sa_dict[j]
                    sa_dict[j] = sa_dict[j + 1]
                    sa_dict[j + 1] = sa_temp


        return JsonResponse({'json_data': sa_dict})
    else:

        return JsonResponse({'json_data': 'feature is null'})


# def append_ad_list(sa_dict, tag, y):
#     r = 10 - len(sa_dict)  # 还差多少个 #
#     sa_tag = '{}{}'.format('image_tag_', y)
#     q = Q()
#     q.add(Q(**{tag: sa_tag}), Q.OR)
#     add_dict = []
#     same_advertisement = Advertisement.objects.exclude(image_feature__isnull=True).exclude(id=ad_id).filter(q)[0:y]
#     add_dict.append([model_to_dict(item) for item in same_advertisement])
#     sa_dict.extend(add_dict[0])
#     return sa_dict
#
#     image_tag_list = []
